package com.engineering.elink.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.engineering.elink.co.CompanyCo;
import com.engineering.elink.co.CompanyDynamicCo;
import com.engineering.elink.co.CompanyInsertCo;
import com.engineering.elink.co.CompanyUpdateCo;
import com.engineering.elink.common.Constant;
import com.engineering.elink.common.ResultType;
import com.engineering.elink.domain.User;
import com.engineering.elink.service.CompanyDynamicService;
import com.engineering.elink.service.CompanyRecordService;
import com.engineering.elink.service.CompanyService;
import com.engineering.elink.service.CookieService;
import com.engineering.elink.service.UserService;
import com.engineering.elink.util.MapConvert;
import com.engineering.elink.util.token.TokenGenerator;
import com.engineering.elink.util.verify.CodeImageGenerator;
import com.engineering.elink.util.verify.VerifyCodeUtils;

@RestController
@RequestMapping("/api/company")
@Api(value = "企业接口")
public class CompanyController {

	@Autowired
	private CompanyService companyService;
	@Autowired
	private CookieService cookieService;
	@Autowired
	private UserService userService;
	@Autowired
	private CompanyRecordService companyRecordService;
	@Autowired
	private CompanyDynamicService companyDynamicService;

	/**
	 * 新增企业记录
	 * 
	 * @param fromUserId
	 * @param toUserId
	 * @return
	 */
	@RequestMapping(value = "addCompanyRecord", method = RequestMethod.POST)
	@ApiOperation(value = "新增企业记录")
	public Map<String, Object> addCompanyRecord(
			@ApiParam(value = "上一家企业ID", required = true) @RequestParam(value = "fromUserId", required = true) String fromUserId,
			@ApiParam(value = "下一家企业ID", required = true) @RequestParam(value = "toUserId", required = true) String toUserId) {
		if (companyRecordService.addCompanyRecord(fromUserId, toUserId)) {
			return MapConvert.getMap(ResultType.SUCCESS);
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);

	}

	@RequestMapping(value = "getCompanyRecordList", method = RequestMethod.GET)
	@ApiOperation(value = "获取企业访问记录")
	public Map<String, Object> getCompanyRecordList(
			@ApiParam(value = "企业ID", required = true) @RequestParam(value = "toUserId", required = true) String toUserId) {
		List<Map<String, Object>> map = companyRecordService.getCompanyRecordList(toUserId);
		if (map != null) {
			return MapConvert.getMap(ResultType.SUCCESS, map);
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);

	}

	@RequestMapping(value = "modifyCompanyInfo", method = RequestMethod.POST)
	@ApiOperation(value = "修改企业信息")
	public Map<String, Object> modifyCompanyInfo(@ModelAttribute("CompanyInfoCo") CompanyUpdateCo CompanyUpdateCo, HttpServletRequest request) {
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			CompanyUpdateCo.setUserId((String) userInfo.get("userId"));
			companyService.updateCompanyInfo(CompanyUpdateCo);
			return MapConvert.getMap(ResultType.SUCCESS);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}

	/**
	 * 获取当前用户的企业基本信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "getBaseInfoByUser", method = RequestMethod.GET)
	@ApiOperation(value = " 获取当前用户的企业基本信息")
	public Map<String, Object> getBaseInfoByUser(HttpServletRequest request) {
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			System.err.println(111);
			return MapConvert.getMap(ResultType.SUCCESS, companyService.getBaseInfoByUserId((String) userInfo.get("userId")));
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}

	/**
	 * 获取其他用户的企业基本信息
	 * 
	 * @param companyId
	 * @return
	 */
	@RequestMapping(value = "getBaseInfoByCompany", method = RequestMethod.GET)
	@ApiOperation(value = " 获取其他用户的企业基本信息")
	public Map<String, Object> getBaseInfoByCompany(
			@ApiParam(value = "企业ID", required = true) @RequestParam(value = "companyId", required = true) String companyId) {
		Map<String, Object> map = companyService.getBaseInfoByCompanyId(companyId);
		if (map != null) {
			return MapConvert.getMap(ResultType.SUCCESS, map);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}

	/**
	 * 企业登录流程一 获取企业登录验证码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/companyLoginWithVerifyCode", method = RequestMethod.GET)
	@ApiOperation(value = "企业登录流程一：获取验证码")
	public Map<String, Object> getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String verifyToken = TokenGenerator.getToken();
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		userService.generateVerifyCode(Constant.verifyCodeCache, verifyToken, verifyCode, Constant.companyLoginCacheOneStepValidTime);
		// 存入验证码缓存中
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("img", CodeImageGenerator.generateBase64Image(verifyCode));
		map.put("verifyToken", verifyToken + "," + Constant.companyLoginCacheOneStepValidTime);
		return MapConvert.getMap(ResultType.SUCCESS, map);
	}

	/**
	 * 企业登录流程二
	 * 
	 * @param email
	 * @param passwd
	 * @param verifyCode
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "companyLogin", method = RequestMethod.POST)
	@ApiOperation(value = "企业登录流程二：提交帐号密码")
	public Map<String, Object> companyLogin(@ApiParam(value = "邮箱") @RequestParam("email") String email,
			@ApiParam(value = "密码") @RequestParam("passwd") String passwd, @ApiParam(value = "验证码") @RequestParam("verifyCode") String verifyCode,
			@ApiParam(value = "令牌") @RequestParam("verifyToken") String verifyToken, HttpServletResponse response, HttpServletRequest request) {
		if (userService.checkVerifyCode(Constant.verifyCodeCache, verifyToken, verifyCode)) {
			Map<String, Object> map = companyService.login(email, passwd);
			if (map != null) {
				String newAuthToken = (userService.refreshAuthToken(((User) map.get("user")).getUserId()));
				String authToken = (newAuthToken == null ? (String) map.get("authToken") : newAuthToken);
				Map<String, Object> authMap = new HashMap<String, Object>();
				authMap.put("seed", (String) map.get("seed") + "," + Constant.verifyCodeForLoginValidTime);
				authMap.put("authToken", authToken + "," + Constant.verifyCodeForLoginValidTime);
				return MapConvert.getMap(ResultType.SUCCESS, authMap);
			} else {
				return MapConvert.getMap(ResultType.PASSWORD_ERROR);
			}
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 企业注册流程一
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/regCompanyWithVerifyCode", method = RequestMethod.GET)
	@ApiOperation(value = "企业注册流程一：获取验证码")
	public Map<String, Object> regCompanyWithVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 生成随机字串
		String verifyToken = TokenGenerator.getToken();
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		System.out.println("验证码为=" + verifyCode);
		// 存入验证码缓存中
		companyService.regCompanyWithVerifyCode(verifyToken, verifyCode);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("img", CodeImageGenerator.generateBase64Image(verifyCode));
		map.put("verifyToken", verifyToken + "," + Constant.companyLoginCacheOneStepValidTime);
		return MapConvert.getMap(ResultType.SUCCESS, map);
	}

	/**
	 * 企业注册流程二
	 * 
	 * @param request
	 * @param response
	 * @param phone
	 * @param verifyCode
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/regCompanyWithSendPhoneCode", method = RequestMethod.POST)
	@ApiOperation(value = "企业注册流程二：发送短信验证码")
	public Map<String, Object> regCompanyWithSendPhoneCode(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "手机号", required = true) @RequestParam(value = "phone", required = true) String phone,
			@ApiParam(value = "验证码", required = true) @RequestParam(value = "verifyCode", required = true) String verifyCode,
			@ApiParam(value = "令牌", required = true) @RequestParam(value = "verifyToken", required = true) String verifyToken) throws IOException {
		if (companyService.regCompanyWithSendPhoneCode(phone, verifyToken, verifyCode)) {
			return MapConvert.getMap(ResultType.SUCCESS);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}

	/**
	 * 企业注册流程三
	 * 
	 * @param request
	 * @param response
	 * @param email
	 * @param phone
	 * @param passwd
	 * @param verifyCode
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/regCompanyWithCheckPhoneCode", method = RequestMethod.POST)
	@ApiOperation(value = "企业注册流程三：校验短信验证码")
	public Map<String, Object> regCompanyWithCheckPhoneCode(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "邮箱", required = true) @RequestParam(value = "email", required = true) String email,
			@ApiParam(value = "手机号", required = true) @RequestParam(value = "phone", required = true) String phone,
			@ApiParam(value = "密码", required = true) @RequestParam(value = "passwd", required = true) String passwd,
			@ApiParam(value = "短信验证码", required = true) @RequestParam(value = "verifyCode", required = true) String verifyCode,
			@ApiParam(value = "令牌", required = true) @RequestParam(value = "verifyToken", required = true) String verifyToken) throws IOException {
		if (companyService.regCompanyWithCheckPhoneCode(email, phone, passwd, verifyToken, verifyCode)) {
			return MapConvert.getMap(ResultType.SUCCESS);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}

	/**
	 * 企业注册流程四
	 * 
	 * @param request
	 * @param response
	 * @param companyCo
	 * @return
	 */
	@RequestMapping(value = "regCompanyWithFillInfo", method = RequestMethod.POST)
	@ApiOperation(value = "企业注册流程四：填写企业信息")
	public Map<String, Object> regCompanyWithFillInfo(HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("CompanyCo") CompanyInsertCo companyCo,
			@ApiParam(value = "令牌", required = true) @RequestParam(value = "verifyToken", required = true) String verifyToken) {
		Map<String, Object> map = companyService.regCompanyWithBaseInfo(companyCo, verifyToken);
		if (map != null) {
			Map<String, Object> authMap = new HashMap<String, Object>();
			authMap.put("seed", (String) map.get("seed") + "," + Constant.verifyCodeForLoginValidTime);
			authMap.put("authToken", (String) map.get("authToken") + "," + Constant.verifyCodeForLoginValidTime);
			return MapConvert.getMap(ResultType.SUCCESS, authMap);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}

	/**
	 * 统计当前用户的企业的概况
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getBasicFacts", method = RequestMethod.GET)
	@ApiOperation(value = "统计当前用户的企业的概况", httpMethod = "GET")
	public Map<String, Object> getBasicFacts(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, companyService.getBasicFacts(userId));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 统计当前用户的企业招聘的信息
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getRecruit", method = RequestMethod.GET)
	@ApiOperation(value = "统计企业招聘的信息", httpMethod = "GET")
	public Map<String, Object> getRecruit(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, companyService.getRecruit(userId));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 统计当前用户的企业资源
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getResource", method = RequestMethod.GET)
	@ApiOperation(value = "统计当前用户的企业资源", httpMethod = "GET")
	public Map<String, Object> getResource(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, companyService.getResource(userId));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 获取当前企业的信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getCurrentCompanyInfo", method = RequestMethod.GET)
	@ApiOperation(value = " 获取当前企业的信息", httpMethod = "GET")
	public Map<String, Object> getCurrentCompanyInfo(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, companyService.getCurrentCompanyInfo(userId));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 获取好评公司
	 * 
	 * @param count
	 * @return
	 */
	@RequestMapping(value = "getPraiseCompany", method = RequestMethod.GET)
	@ApiOperation(value = " 获取好评公司", httpMethod = "GET")
	public Map<String, Object> getPraiseCompany(
			@ApiParam(value = "返回数据的条数", required = false, defaultValue = "10") 
			@RequestParam(value = "count", required = false, defaultValue = "10") int count) {
		return MapConvert.getMap(ResultType.SUCCESS, companyService.getPraiseCompany(count));
	}

	/**
	 * 统计公司数，点评数,发布招聘数
	 * 
	 * @return
	 */
	@RequestMapping(value = "getStatistics", method = RequestMethod.GET)
	@ApiOperation(value = " 统计公司数，点评数,发布招聘数", httpMethod = "GET")
	public Map<String, Object> getStatistics() {
		return MapConvert.getMap(ResultType.SUCCESS, companyService.getStatistics());
	}

	/**
	 * 根据条件搜索公司
	 * 
	 * @param co
	 * @return
	 */
	@RequestMapping(value = "getCompanyList", method = RequestMethod.GET)
	@ApiOperation(value = " 公司列表", httpMethod = "GET", notes = "根据条件搜索公司分页列表")
	public Map<String, Object> getCompanyList(@ModelAttribute @Valid CompanyCo co) {
		return MapConvert.getMap(ResultType.SUCCESS, companyService.getCompanyList(co));
	}

	/**
	 * 获取企业动态
	 * 
	 * @param companyDynamicCo
	 * @return
	 */
	@RequestMapping(value = "getCompanyDynamicList", method = RequestMethod.GET)
	@ApiOperation(value = " 获取企业动态")
	public Map<String, Object> getCompanyDynamicList(@ModelAttribute("CompanyDynamicCo") @Valid CompanyDynamicCo companyDynamicCo) {
		return MapConvert.getMap(ResultType.SUCCESS, companyDynamicService.getCompanyDynamicList(companyDynamicCo));
	}
}
